package com.sun.module_base.app

import com.sun.module_base.network.error.ExceptionHandle
import com.sun.module_network.ApiException
import com.sun.module_network.BaseResponse
import com.sun.module_network.Error
import com.sun.module_network.createException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update

/**
 *@author:sunc
 *@time :2025/7/18 16:43
 *@desc:  自定义结果集封装类
 */
sealed class ResultState<out T> {
    data class Loading(val loadingMsg: String = "请求网络中...") : ResultState<Nothing>()
    data class Success<out T>(val data: T?) : ResultState<T>()
    data class Error(val error: ApiException) : ResultState<Nothing>()
}

fun <T> MutableStateFlow<ResultState<T>>.parseResult(result: BaseResponse<T>) {
//    update { it -> //update 为原子操作，线程安全
    value = when {
        result.isSuccess() -> {
            ResultState.Success(result.getResponseData())
        }

        else -> ResultState.Error(Error.HTTP_ERROR.createException(code = result.getResponseCode(), message = result.getResponseMsg()))
    }
}
//}

fun <T> MutableStateFlow<ResultState<T>>.parseResult(result: T) {
//    update { ResultState.Success(result) }
    value = ResultState.Success(result)
}

fun <T> MutableStateFlow<ResultState<T>>.parseException(e: Throwable) {
//    update { ResultState.Error(ExceptionHandle.handlerException(e)) }
    value = ResultState.Error(ExceptionHandle.handlerException(e))
}